package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.client.UserClient;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static com.leyou.auth.constants.JwtConstants.DOMAIN;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Service
public class UserAuthServiceImpl  implements UserAuthService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //根据用户名和密码查询
            UserDTO userDTO = userClient.queryUserByUsernameAndPassword(username, password);
            //查看查询结果是否存在
            if (userDTO == null) {
                throw new LyException(400, "用户名获取密码错误");
            }
            //正确后生成一个jwt
            String jwt = jwtUtils.createJwt(UserDetails.of(userDTO.getId(), userDTO.getUsername()));
            //将用户信息写入cookie
            writeCookie(response, jwt);
        }catch (FeignException e){
            throw new LyException(e.status(),e.getMessage());
        }
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        //判断是否登录
        if (StringUtils.isBlank(jwt)){
            return;
        }
        try {
            //解析用户获取用户id
            Payload payload = jwtUtils.parseJwt(jwt);
            Long userId = payload.getUserDetail().getId();
            //删除redis中的jti
            jwtUtils.clearJwt(userId);
        }catch (Exception e){
            //判断用户未登录无需删除redis
        }

        //删除cookie
        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME, DOMAIN, response);
    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, jwt);
        //cookie的作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        //是否禁止js操作cookie
        cookie.setHttpOnly(true);
        //cookie有效操作，-1随机会话
        cookie.setMaxAge(-1);
        //cookie作用路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
